package my.client.security;

import my.client.security.beans.Request;
import my.client.security.beans.Response;
import my.client.security.beans.UserCredentials;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.AuthenticationException;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.providers.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.ws.client.core.WebServiceTemplate;

public class AuthenticationProvider extends
		AbstractUserDetailsAuthenticationProvider {

	private WebServiceTemplate wstemplate;
	
	private String wsUri;


	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	protected void additionalAuthenticationChecks(UserDetails user,
			UsernamePasswordAuthenticationToken token)
			throws AuthenticationException {
		logger.debug("User ={}", user);
		logger.debug("Token ={}", token);

	}

	@Override
	protected UserDetails retrieveUser(String userId,
			UsernamePasswordAuthenticationToken token)
			throws AuthenticationException {
		logger.debug("Principal ={}", token.getPrincipal());
		logger.debug("Credentials ={}", token.getCredentials());
		logger.debug("Token details ={}", token.getDetails());
		UserCredentials userCredentials = new UserCredentials();
		userCredentials.setUserId(userId);
		userCredentials.setPassword(token.getCredentials().toString());
		Request request = new Request();
		request.setUserCredentials(userCredentials);
		Response response = (Response) wstemplate.marshalSendAndReceive(wsUri, request);
		UserDetails userDetails = response.getUserDetails();
		logger.debug("UserDetails ={}", userDetails);
		return userDetails;
	}

	public void setWsUri(String wsUri) {
		this.wsUri = wsUri;
	}
	
	public void setWstemplate(WebServiceTemplate wstemplate) {
		this.wstemplate = wstemplate;
	}

}
